
#import "GestureViewController.h"
#import "PCCircleView.h"
#import "PCCircleViewConst.h"
#import "PCLockLabel.h"
#import "PCCircleInfoView.h"
#import "PCCircle.h"

//#import "ZHRT_Header.h"
//#import "ZHRTMyHomeModel.h"
#import "XDLMRootViewController.h"
#import "XDLMNavigatonController.h"
//#import "ZHRTCustomFrame.h"

//#import "ZHRTUserCertenModel.h"
#import "UIImageView+WebCache.h"
#import "ZHRTBasicMethod.h"
#import "XDLMLoginViewController.h"
#import "XDLMGestureViewController.h"
@interface GestureViewController ()<CircleViewDelegate, UIAlertViewDelegate>

/**
 *  重设按钮
 */
@property (nonatomic, strong) UIButton *resetBtn;

/**
 *  提示Label
 */
@property (nonatomic, strong) PCLockLabel *msgLabel;

/**
 *  解锁界面
 */
@property (nonatomic, strong) PCCircleView *lockView;

/**
 *  infoView
 */
@property (nonatomic, strong) PCCircleInfoView *infoView;

@end

@implementation GestureViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (self.type == GestureViewControllerTypeLogin) {
        [self.navigationController setNavigationBarHidden:YES animated:animated];
    }
    
    // 进来先清空存的第一个密码
    [PCCircleViewConst saveGesture:nil Key:gestureOneSaveKey];
}

- (instancetype)init
{
    self = [super init];
    if (self) {

    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    [self.view setBackgroundColor:CircleViewBackgroundColor];
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"login_bg"]]]; 
    // 1.界面相同部分生成器
    [self setupSameUI];
   self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    // 2.界面不同部分生成器
    [self setupDifferentUI];
}

#pragma mark - 创建UIBarButtonItem
- (UIBarButtonItem *)itemWithTitle:(NSString *)title target:(id)target action:(SEL)action tag:(NSInteger)tag
{
    UIButton *button = [[UIButton alloc] init];
    [button setTitle:title forState:UIControlStateNormal];
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    button.frame = (CGRect){CGPointZero, {50, 20}};
    [button setTitleColor:kColorRGB(187,147,115)forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:17];
    button.tag = tag;
    [button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    [button setHidden:YES];
    //self.resetBtn = button;
    
    return [[UIBarButtonItem alloc] initWithCustomView:button];
}

#pragma mark - 界面不同部分生成器
- (void)setupDifferentUI
{
    switch (self.type) {
        case GestureViewControllerTypeSetting:
            [self setupSubViewsSettingVc];
            break;
        case GestureViewControllerTypeLogin:
            [self setupSubViewsLoginVc];
            break;
        default:
            break;
    }
}

#pragma mark - 界面相同部分生成器
- (void)setupSameUI
{
    // 创建导航栏右边按钮
//    self.navigationItem.rightBarButtonItem = [self itemWithTitle:@"重设" target:self action:@selector(didClickBtn:) tag:buttonTagReset];
    
    // 解锁界面
    PCCircleView *lockView = [[PCCircleView alloc] init];
    lockView.delegate = self;
    self.lockView = lockView;
    [self.view addSubview:lockView];
    
    PCLockLabel *msgLabel = [[PCLockLabel alloc] init];
    msgLabel.frame = [ZHRTBasicMethod createFrame:CGRectMake(0, 140, kScreenW, 20)];
    msgLabel.center = CGPointMake(kScreenW/2, CGRectGetMinY(lockView.frame) - 30);
    self.msgLabel = msgLabel;
    msgLabel.textColor = kColor_97_100_108;
    [self.view addSubview:msgLabel];
}

#pragma mark - 设置手势密码界面
- (void)setupSubViewsSettingVc
{
    [self.lockView setType:CircleViewTypeSetting];
    
    self.title = @"设置手势密码";
    [self.msgLabel showNormalMsg:gestureTextBeforeSet];
    
    PCCircleInfoView *infoView = [[PCCircleInfoView alloc] init];
    infoView.frame = CGRectMake(0, 0, CircleRadius * 2 * 0.6, CircleRadius * 2 * 0.6);
    infoView.center = CGPointMake(kScreenW/2, CGRectGetMinY(self.msgLabel.frame) - CGRectGetHeight(infoView.frame)/2 - 10);
    self.infoView = infoView;
    self.msgLabel.textColor = kColor_97_100_108;
    [self.view addSubview:infoView];
}

#pragma mark - 登陆手势密码界面
- (void)setupSubViewsLoginVc
{

    NSUserDefaults * df = [NSUserDefaults standardUserDefaults];
    
    
    
    [self.lockView setType:CircleViewTypeLogin];
    
    // 头像
//    UIImageView  *imageView = [[UIImageView alloc] init];
//    imageView.frame = [ZHRTBasicMethod createFrame:CGRectMake((kScreenW - 60 * kScreenH / 568)*0.5, 112/2, 60 * kScreenH / 568, 60)];
//    imageView.center = CGPointMake(kScreenW/2, kScreenH/6);
//    imageView.backgroundColor = [UIColor whiteColor];
//    imageView.layer.cornerRadius =  60 * kScreenH / 568 / 2;
//    
//    imageView.clipsToBounds = YES;
    
//   [imageView sd_setImageWithURL:[NSURL URLWithString:model.icon] placeholderImage:[UIImage imageNamed:@"touxiang"]];
    
//    [self.view addSubview:imageView];
//    if ([df objectForKey:@"ico"]) {
//        [imageView sd_setImageWithURL:[NSURL URLWithString:[df objectForKey:@"ico"]] placeholderImage:[UIImage imageNamed:@"logo"]];
//    }else{
//        [imageView setImage:[UIImage imageNamed:@"logo"]];
//    }
//    
    UILabel * title = [[UILabel alloc] initWithFrame:[ZHRTBasicMethod createFrame:CGRectMake(0, 116 + 23, kScreenW, 20)]];
    title.textColor = kColor_97_100_108;
    title.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:title];
    title.text = [[df objectForKey:@"mobile"] stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@" **** "];;
    
    // 管理手势密码
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self creatButton:leftBtn frame:CGRectMake(0, kScreenH - 60, kScreenW, 20) title:@"管理手势密码" alignment:UIControlContentHorizontalAlignmentCenter tag:buttonTagManager];
    [leftBtn setTitleColor:kColor_97_100_108 forState:UIControlStateNormal];
    // 登录其他账户
//    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [self creatButton:rightBtn frame:CGRectMake(kScreenW/2 - CircleViewEdgeMargin - 20, kScreenH - 60, kScreenW/2, 20) title:@"切换账户" alignment:UIControlContentHorizontalAlignmentRight tag:buttonTagForget];
//    [rightBtn setTitleColor:kColor_97_100_108 forState:UIControlStateNormal];

}

#pragma mark - 创建UIButton
- (void)creatButton:(UIButton *)btn frame:(CGRect)frame title:(NSString *)title alignment:(UIControlContentHorizontalAlignment)alignment tag:(NSInteger)tag
{
    btn.frame = frame;
    btn.tag = tag;
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn setContentHorizontalAlignment:alignment];
    [btn.titleLabel setFont:[UIFont systemFontOfSize:14.0f]];
    [btn addTarget:self action:@selector(didClickBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
}

#pragma mark - button点击事件
- (void)didClickBtn:(UIButton *)sender
{

    switch (sender.tag) {
        case buttonTagReset:
        {
    
//            点击了重设按钮
            // 1.隐藏按钮
            [self.resetBtn setHidden:YES];
            
            // 2.infoView取消选中
            [self infoViewDeselectedSubviews];
            
            // 3.msgLabel提示文字复位
            [self.msgLabel showNormalMsg:gestureTextBeforeSet];
            
            // 4.清除之前存储的密码
            [PCCircleViewConst saveGesture:nil Key:gestureOneSaveKey];
        }
            break;
        case buttonTagManager:
        {
//         点击了管理手势密码按钮
//            [self.navigationController pushViewController:VC animated:YES];
            UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"忘记手势密码，需重新登录！" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alertView show];
            alertView.tag =  10000;
            
        }
            break;
        case buttonTagForget:{
//            点击了登录其他账户按钮
            UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"切换账户会注销已登录账号，是否继续？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alertView show];
            alertView.tag =  10001;
           
        }
            
            
            break;
        default:
            break;
    }
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    
    if (alertView.tag == 10000 && buttonIndex == 1) {
        XDLMLoginViewController * VC = [[XDLMLoginViewController alloc] init];
        VC.isGestureUserPassword = YES;
        VC.isUserName = YES;
        //            VC.myTag = YES;
        XDLMNavigatonController * na = [[XDLMNavigatonController alloc] initWithRootViewController:VC];
        [self presentViewController:na animated:YES completion:nil];
    } else {
    
    }
}
#pragma mark - circleView - delegate
#pragma mark - circleView - delegate - setting
- (void)circleView:(PCCircleView *)view type:(CircleViewType)type connectCirclesLessThanNeedWithGesture:(NSString *)gesture
{
    NSString *gestureOne = [PCCircleViewConst getGestureWithKey:gestureOneSaveKey];

    // 看是否存在第一个密码
    if ([gestureOne length]) {
        [self.resetBtn setHidden:NO];
        [self.msgLabel showWarnMsgAndShake:gestureTextDrawAgainError];
    } else {
//        密码长度不合法
        [self.msgLabel showWarnMsgAndShake:gestureTextConnectLess];
    }
}

- (void)circleView:(PCCircleView *)view type:(CircleViewType)type didCompleteSetFirstGesture:(NSString *)gesture
{
//    获得第一个手势密码
    [self.msgLabel showWarnMsg:gestureTextDrawAgain];
    
    // infoView展示对应选中的圆
    [self infoViewSelectedSubviewsSameAsCircleView:view];
}

- (void)circleView:(PCCircleView *)view type:(CircleViewType)type didCompleteSetSecondGesture:(NSString *)gesture result:(BOOL)equal
{
//    获得第二个手势密码
    if (equal) {

//        两次手势匹配！可以进行本地化保存了
        [self.msgLabel showWarnMsg:gestureTextSetSuccess];
        [PCCircleViewConst saveGesture:gesture Key:gestureFinalSaveKey];
//        [self dismissViewControllerAnimated:YES completion:nil];
        NSInteger count = 0;
        for (UIViewController *vc in self.navigationController.viewControllers) {
            count ++;
            if ([vc isKindOfClass:[XDLMGestureViewController class]]) {
                
                [self.navigationController popToViewController:vc animated:YES];
                
            } else if (count == self.navigationController.viewControllers.count) {

                    [self.navigationController popViewControllerAnimated:YES];
            }
        }
        
//        NSArray * array = [self.navigationController viewControllers];
//        UIViewController * vc = [array objectAtIndex:0];
//        [self.navigationController popToViewController:vc animated:YES];
        
    } else {
//        两次手势不匹配！
        [self infoViewDeselectedSubviews];
        
        // 3.msgLabel提示文字复位
        [self.msgLabel showNormalMsg:gestureTextBeforeSet];
        
        // 4.清除之前存储的密码
        [PCCircleViewConst saveGesture:nil Key:gestureOneSaveKey];

        [self.msgLabel showWarnMsgAndShake:gestureTextDrawAgainError];
        [self.resetBtn setHidden:NO];
    }
}

#pragma mark - circleView - delegate - login or verify gesture
- (void)circleView:(PCCircleView *)view type:(CircleViewType)type didCompleteLoginGesture:(NSString *)gesture result:(BOOL)equal
{
    // 此时的type有两种情况 Login or verify
    if (type == CircleViewTypeLogin) {
        NSUserDefaults * df = [NSUserDefaults standardUserDefaults];
        
       
        
        if (equal) {
            if ([df objectForKey:@"tag"]) {
                 [df removeObjectForKey:@"tag"];
                [df synchronize];
            }

//            登陆成功！
            [[NSNotificationCenter defaultCenter] postNotificationName:@"passwordLock" object:nil];
        } else {
            if ([df objectForKey:@"tag"]) {
                NSNumber * tag = [df objectForKey:@"tag"];
                NSInteger count = [tag integerValue];
                if (count == 5) {
                    //强制登录
                    XDLMLoginViewController * login = [[XDLMLoginViewController alloc] init];
                    XDLMNavigatonController * nav = [[XDLMNavigatonController alloc] initWithRootViewController:login];
                    login.isGestureUserPassword = YES;
                    login.isUserName = YES;
                    [self presentViewController:nav animated:YES completion:nil];
                }else {
                    count += 1;
                    [df setObject:[NSNumber numberWithInteger:count] forKey:@"tag"];
                    

                }
              
                               //判断几次
            }else {
                //插入tag
              //  NSString * tag = @"1";
                [df setObject:@"1" forKey:@"tag"];
                [df synchronize];
            }

//            密码错误！
            [self.msgLabel showWarnMsgAndShake:gestureTextGestureVerifyError];
        }
    } else if (type == CircleViewTypeVerify) {
        
        if (equal) {
        
//           验证成功，跳转到设置手势界面
        } else {
//            原手势密码输入错误

            
        }
    }
}

#pragma mark - infoView展示方法
#pragma mark - 让infoView对应按钮选中
- (void)infoViewSelectedSubviewsSameAsCircleView:(PCCircleView *)circleView
{
    for (PCCircle *circle in circleView.subviews) {
        
        if (circle.state == CircleStateSelected || circle.state == CircleStateLastOneSelected) {
            
            for (PCCircle *infoCircle in self.infoView.subviews) {
                if (infoCircle.tag == circle.tag) {
                    [infoCircle setState:CircleStateSelected];
                }
            }
        }
    }
}

#pragma mark - 让infoView对应按钮取消选中
- (void)infoViewDeselectedSubviews
{
    [self.infoView.subviews enumerateObjectsUsingBlock:^(PCCircle *obj, NSUInteger idx, BOOL *stop) {
        [obj setState:CircleStateNormal];
    }];
}

- (void)back{
    
    NSInteger count = 0;
    for (UIViewController *vc in self.navigationController.viewControllers) {
         count ++;
        if ([vc isKindOfClass:[XDLMGestureViewController class]]) {
            
            [self.navigationController popToViewController:vc animated:YES];
            
        } else if ([vc isKindOfClass:[XDLMLoginViewController class]]){
            [self dismissViewControllerAnimated:YES completion:nil];
        
        }else if (count == self.navigationController.viewControllers.count){
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    
}



@end
